package com.hua.demo.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.hua.demo.edu.entity.Subject;
import com.hua.demo.edu.entity.excel.SubjectData;
import com.hua.demo.edu.entity.subject.OneSubject;
import com.hua.demo.edu.entity.subject.TwoSubject;
import com.hua.demo.edu.listener.SubjectExcelListener;
import com.hua.demo.edu.mapper.SubjectMapper;
import com.hua.demo.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author huazi
 * @since 2021-11-19
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {



    @Override
    public void savesubject(MultipartFile file, SubjectService subjectService) {
        try {
            InputStream in=file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    //查询所有banner
    @Cacheable(value = "banner",key = "'selectIndexList'")
    public List<OneSubject> getallonetwosubject() {
        QueryWrapper<Subject> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        List<Subject> list = this.list(wrapper);

        QueryWrapper<Subject> wrapper1=new QueryWrapper<>();
        wrapper1.ne("parent_id","0");
        List<Subject> list1= this.list(wrapper1);

        List<OneSubject> finalsubject=new ArrayList<>();


        //封装一级分类
        for (Subject subject : list) {
            OneSubject oneSubject = new OneSubject();
//            oneSubject.setId(subject.getId());
//            oneSubject.setTitle(subject.getTitle());
            //简化方法
            BeanUtils.copyProperties(subject,oneSubject);

            finalsubject.add(oneSubject);
            List<TwoSubject> finaltwosubject=new ArrayList<>();
            for (Subject subject1 : list1) {


                if(oneSubject.getId().equals(subject1.getParentId())){
                    TwoSubject twoSubject = new TwoSubject();
                    twoSubject.setId(subject1.getId());
                    twoSubject.setTitle(subject1.getTitle());
                    finaltwosubject.add(twoSubject);
                }
            }oneSubject.setChildren(finaltwosubject);
        }

        return finalsubject;
    }
}
